package n7_wait_notify;

import lombok.extern.slf4j.Slf4j;

import static utils.Sleeper.sleep;

/**
 * 获得锁的sleep不会释放锁， 但是wait会释放
 */
@Slf4j(topic = "c.T3")
public class T3_wait_sleep_区别 {

    static final Object lock = new Object();
    public static void main(String[] args) {

        log.debug("main ======= beg =========");

//        sleepTest();
        waitTest();


    }
    // sleep 不会释放锁，想要获取锁的主线程一直等下去
    private static void sleepTest(){
        new Thread(()->{

            synchronized (lock){
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();

        sleep(1);

        synchronized (lock){
            log.debug("----- 获得锁 -----");
        }
    }

    // wait 会释放锁
    private static void waitTest(){
        new Thread(()->{
            synchronized (lock){
                try {
                    log.debug("----- wait开始 --------------------");
                    lock.wait(10000);
                    log.debug("----- wait结束 --------------------");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();

        sleep(1);

        synchronized (lock){
            log.debug("----- sleep开始 -----");
            sleep(5);
            log.debug("----- sleep结束 -----");
        }
    }

}
